<template>
  <view class="login-container">
    <!-- 顶部导航栏 -->
    <view class="header-bar">
      <view class="header-content">
        <view class="logo-section">
          <image class="logo-image" src="@/static/image/OAlogo.png" mode="aspectFit"></image>
          <text class="header-title">政务服务平台</text>
        </view>
      </view>
    </view>

    <!-- 主体内容 -->
    <view class="main-content">
      <!-- 登录表单 -->
      <view class="login-card">
        <text class="login-title">用户登录</text>

        <!-- 用户名输入 -->
        <view class="input-group">
          <view class="input-icon">
            <text class="icon-text">👤</text>
          </view>
          <u-input
            v-model="formData.username"
            placeholder="请输入用户名（2-20个字符）"
            border="none"
            :clearable="true"
            size="large"
            shape="round"
            :custom-style="inputStyle"
          />
        </view>

        <!-- 密码输入 -->
        <view class="input-group">
          <view class="input-icon">
            <text class="icon-text">🔒</text>
          </view>
          <u-input
            v-model="formData.password"
            placeholder="请输入密码（6-20个字符）"
            :password="!showPassword"
            :password-visibility-toggle="true"
            border="none"
            :clearable="false"
            size="large"
            shape="round"
            :custom-style="inputStyle"
          />
        </view>

        <!-- 记住密码和忘记密码 -->
        <view class="form-options">
          <u-checkbox-group v-model="checkboxValue">
            <u-checkbox :name="true" active-color="#1e90ff" size="18">
              <text class="remember-text">记住密码</text>
            </u-checkbox>
          </u-checkbox-group>
          <u-link text="记住密码" color="#1e90ff" />
        </view>

        <!-- 登录按钮 -->
        <u-button
          :loading="isLoading"
          :disabled="isLoading"
          @click="submit"
          type="primary"
          size="large"
          shape="round"
          :custom-style="buttonStyle"
        >
          {{ isLoading ? '登录中...' : '登录' }}
        </u-button>
      </view>

      <view class="version-info">
        <text class="version-text">当前版本：{{ appVersion }}</text>
      </view>

      <!-- 服务标语 -->
      <view class="service-slogan">
        <text class="slogan-text">打造高效便民的数字化政务服务</text>
      </view>

      <!-- 服务功能 -->
      <!-- <view class="service-features">
        <view class="feature-item">
          <view class="feature-icon">
            <text class="icon-text">📋</text>
          </view>
          <text class="feature-text">在线办理</text>
        </view>
        <view class="feature-item">
          <view class="feature-icon">
            <text class="icon-text">🔍</text>
          </view>
          <text class="feature-text">进度查询</text>
        </view>
        <view class="feature-item">
          <view class="feature-icon">
            <text class="icon-text">💬</text>
          </view>
          <text class="feature-text">在线咨询</text>
        </view>
      </view> -->
    </view>

    <!-- 底部信息 -->
    <!--    <view class="footer">-->
    <!--      <view class="footer-icons">-->
    <!--        <view class="footer-icon">-->
    <!--          <text class="icon-text">🛡️</text>-->
    <!--        </view>-->
    <!--        <view class="footer-icon">-->
    <!--          <text class="icon-text">⚙️</text>-->
    <!--        </view>-->
    <!--      </view>-->
    <!--      <text class="footer-text">© 2023 政务服务平台 版权所有</text>-->
    <!--      <text class="footer-text">京 ICP 备 12345678 号 - 1</text>-->
    <!--    </view>-->
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { login } from '@/Api/load/load'
import { UserManager } from '@/utils/user'
import envConfig from '@/config/env'
import { VERSION_STORAGE_KEY, getCachedVersionInfo, type CachedVersionInfo } from '@/utils/update'

// 表单引用
const formRef = ref()

// 登录表单数据
const formData = reactive({
  username: '',
  password: '',
})

// 表单验证规则
const rules = {
  username: [
    {
      required: true,
      message: '用户名不能为空',
      trigger: ['blur', 'change'],
    },
    {
      min: 2,
      max: 20,
      message: '用户名长度必须在2-20个字符之间',
      trigger: ['blur', 'change'],
    },
  ],
  password: [
    {
      required: true,
      message: '密码不能为空',
      trigger: ['blur', 'change'],
    },
    {
      min: 6,
      max: 20,
      message: '密码长度必须在6-20个字符之间',
      trigger: ['blur', 'change'],
    },
  ],
}

// 登录状态
const isLoading = ref(false)
const showPassword = ref(false) // 默认隐藏密码
const isRemembered = ref(false)
const checkboxValue = ref<boolean[]>([])

const appVersion = ref(`v${envConfig.version}`)
const versionCache = ref<CachedVersionInfo | null>(null)

const parseVersionCode = (value: unknown): number => {
  const num = Number(value)
  return Number.isFinite(num) ? num : 0
}

const applyVersionDisplay = (versionName?: string, versionCode?: number | string): boolean => {
  if (!versionName) return false
  const cleanName = `${versionName}`.trim()
  if (!cleanName) return false
  const normalized =
    cleanName.startsWith('v') || cleanName.startsWith('V') ? cleanName.slice(1) : cleanName
  const codeStr =
    versionCode !== undefined && versionCode !== null && `${versionCode}`.toString().trim() !== ''
      ? ` (${versionCode})`
      : ''
  appVersion.value = `v${normalized}${codeStr}`
  return true
}

const updateLocalVersionCache = (info: CachedVersionInfo) => {
  if (!info.versionName) return
  try {
    if (typeof uni === 'undefined') return
    const payload: CachedVersionInfo = {
      versionName: info.versionName,
      versionCode: info.versionCode,
      updateType: info.updateType,
      timestamp: Date.now(),
    }
    uni.setStorageSync(VERSION_STORAGE_KEY, payload)
    versionCache.value = payload
  } catch (error) {
    console.warn('[login] 缓存版本信息失败:', error)
  }
}

const loadAppVersion = () => {
  try {
    const cached = getCachedVersionInfo()
    if (cached) {
      versionCache.value = cached
      applyVersionDisplay(cached.versionName, cached.versionCode)
    }
  } catch (error) {
    console.warn('[login] 读取缓存版本信息失败:', error)
  }

  // #ifdef APP-PLUS
  const applyRuntimeInfo = (version?: string, code?: any) => {
    if (!version) return
    const runtimeCode = parseVersionCode(code)
    const cachedCode = versionCache.value ? parseVersionCode(versionCache.value.versionCode) : -1
    if (!versionCache.value || runtimeCode > cachedCode) {
      applyVersionDisplay(version, runtimeCode || '')
      updateLocalVersionCache({
        versionName: version,
        versionCode: runtimeCode || code,
        updateType: 'runtime',
      })
    }
  }

  const setVersion = (info?: any) => {
    if (!info || !info.version) return
    applyRuntimeInfo(info.version, info.versionCode || info.versionCodeRaw)
  }

  try {
    const fetchVersion = () => {
      try {
        const appid = plus.runtime.appid
        applyRuntimeInfo(plus.runtime.version, plus.runtime.versionCode)
        if (!appid) {
          console.warn('[login] 获取 appid 失败，使用默认版本号')
          return
        }
        plus.runtime.getProperty(appid, (info) => setVersion(info))
      } catch (innerError) {
        console.warn('[login] 读取运行时版本失败:', innerError)
      }
    }

    if (typeof uni !== 'undefined') {
      const plusReady = (uni as any).plusReady
      if (typeof plusReady === 'function') {
        plusReady(() => fetchVersion())
        return
      }
    }

    if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
      const doc = window.document
      const handler: EventListener = () => {
        fetchVersion()
        doc.removeEventListener('plusready', handler)
      }
      doc.addEventListener('plusready', handler)
    } else if (typeof plus !== 'undefined') {
      fetchVersion()
    }
  } catch (error) {
    console.warn('[login] 读取运行时版本失败:', error)
  }
  // #endif
}

// 保存密码相关常量
const SAVED_CREDENTIALS_KEY = 'saved_credentials'
const REMEMBER_ME_KEY = 'remember_me'

// 样式配置
const inputStyle = {
  height: '88rpx',
  fontSize: '32rpx',
  paddingLeft: '80rpx',
  border: '2rpx solid #1e90ff',
  borderRadius: '16rpx',
  backgroundColor: '#ffffff',
  boxShadow: '0 2rpx 8rpx rgba(30, 144, 255, 0.1)',
  transition: 'all 0.3s ease',
}

const buttonStyle = {
  height: '80rpx',
  fontSize: '32rpx',
  background: 'linear-gradient(to right, #1e90ff, #00bfff)',
  border: 'none',
}

// 切换密码显示
const togglePassword = () => {
  showPassword.value = !showPassword.value
  console.log('密码显示状态:', showPassword.value)
}

// 监听复选框变化
watch(
  checkboxValue,
  (newValue) => {
    isRemembered.value = newValue.includes(true)
  },
  { deep: true },
)

// 保存登录凭据
const saveCredentials = (username: string, password: string) => {
  try {
    const credentials = {
      username: username,
      password: password,
      timestamp: Date.now(),
    }
    uni.setStorageSync(SAVED_CREDENTIALS_KEY, credentials)
    uni.setStorageSync(REMEMBER_ME_KEY, true)
    console.log('登录凭据已保存')
  } catch (error) {
    console.error('保存登录凭据失败:', error)
  }
}

// 加载保存的登录凭据
const loadSavedCredentials = () => {
  try {
    const rememberMe = uni.getStorageSync(REMEMBER_ME_KEY)
    if (rememberMe) {
      const credentials = uni.getStorageSync(SAVED_CREDENTIALS_KEY)
      if (credentials && credentials.username && credentials.password) {
        formData.username = credentials.username
        formData.password = credentials.password
        isRemembered.value = true
        checkboxValue.value = [true]
        console.log('已加载保存的登录凭据')
        return true
      }
    }
    return false
  } catch (error) {
    console.error('加载保存的登录凭据失败:', error)
    return false
  }
}

// 清除保存的登录凭据
const clearSavedCredentials = () => {
  try {
    uni.removeStorageSync(SAVED_CREDENTIALS_KEY)
    uni.removeStorageSync(REMEMBER_ME_KEY)
    console.log('已清除保存的登录凭据')
  } catch (error) {
    console.error('清除保存的登录凭据失败:', error)
  }
}

// 登录提交
const submit = async () => {
  // 手动表单验证
  if (!formData.username) {
    uni.showToast({
      title: '请输入用户名',
      icon: 'none',
    })
    return
  }

  if (formData.username.length < 2 || formData.username.length > 20) {
    uni.showToast({
      title: '用户名长度必须在2-20个字符之间',
      icon: 'none',
    })
    return
  }

  if (!formData.password) {
    uni.showToast({
      title: '请输入密码',
      icon: 'none',
    })
    return
  }

  if (formData.password.length < 6 || formData.password.length > 20) {
    uni.showToast({
      title: '密码长度必须在6-20个字符之间',
      icon: 'none',
    })
    return
  }

  isLoading.value = true

  try {
    console.log('开始登录，用户名:', formData.username)

    // 密码登录
    const response = await login({
      username: formData.username,
      password: formData.password,
      rememberMe: isRemembered.value,
    })

    console.log('登录响应:', response)

    // 保存用户信息和token
    if (response.data) {
      console.log('保存用户信息:', response.data)

      // 保存用户信息到 store
      if (response.data.userInfo) {
        UserManager.setUserInfo(response.data.userInfo)
      }

      // 保存 token（始终保存）
      if (response.data.token) {
        uni.setStorageSync('token', response.data.token)
        console.log('Token 已保存')
      }

      // 保存 refreshToken（始终保存，用于自动刷新令牌）
      if (response.data.refreshToken) {
        uni.setStorageSync('refreshToken', response.data.refreshToken)
        console.log('RefreshToken 已保存')
      }

      // 如果选择了记住密码，保存登录凭据（用户名和密码）
      if (isRemembered.value) {
        saveCredentials(formData.username, formData.password)
        console.log('已保存登录凭据（用户名和密码）')
      } else {
        // 如果没有选择记住密码，清除之前保存的凭据（但保留 refreshToken）
        clearSavedCredentials()
        console.log('已清除登录凭据（但保留 refreshToken）')
      }

      // 检查系统激活和过期状态
      const expireNoticeDays = response.data.expireNoticeDays
      const expireDate = response.data.expireDate

      if (expireNoticeDays !== undefined && expireNoticeDays !== null) {
        // 系统已过期（负数天数）
        if (expireNoticeDays < 0) {
          uni.showModal({
            title: '⚠️ 系统已到期',
            content: `系统已于 ${expireDate} 到期，请尽快联系管理员续费！\n\n您是管理员账号，允许登录进行系统管理。`,
            showCancel: false,
            confirmText: '我知道了',
            confirmColor: '#ff4444',
          })
        }
        // 今天到期
        else if (expireNoticeDays === 0) {
          uni.showModal({
            title: '⚠️ 系统今日到期',
            content: `系统将于今天（${expireDate}）到期，请立即联系管理员续费！`,
            showCancel: false,
            confirmText: '我知道了',
            confirmColor: '#ff9800',
          })
        }
        // 15天内即将到期
        else if (expireNoticeDays > 0 && expireNoticeDays <= 15) {
          uni.showModal({
            title: '⏰ 系统即将到期',
            content: `系统将于 ${expireNoticeDays} 天后（${expireDate}）到期，请及时联系管理员续费。`,
            showCancel: false,
            confirmText: '我知道了',
            confirmColor: '#ff9800',
          })
        }
      }

      uni.showToast({
        title: '登录成功',
        icon: 'success',
        duration: 1500,
      })

      // 登录成功后立即注册设备（不等待onShow）
      // #ifdef APP-PLUS
      setTimeout(async () => {
        try {
          console.log('[Login] 登录成功，立即注册设备')
          // 触发全局事件，通知 App.vue 注册设备
          uni.$emit('user-logged-in')
        } catch (error) {
          console.error('[Login] 触发设备注册事件失败:', error)
        }
      }, 500)
      // #endif

      // 跳转到首页
      setTimeout(() => {
        console.log('准备跳转到主页面')
        uni.reLaunch({
          url: '/pages/index/index',
          success: () => {
            console.log('跳转成功')
          },
          fail: (err) => {
            console.error('跳转失败:', err)
            // 如果跳转失败，尝试使用 navigateTo
            uni.navigateTo({
              url: '/pages/index/index',
            })
          },
        })
      }, 1500)
    } else {
      throw new Error('登录响应数据格式错误')
    }
  } catch (error) {
    console.error('登录失败:', error)
    uni.showToast({
      title: (error as any)?.message || '登录失败，请重试',
      icon: 'none',
      duration: 3000,
    })
  } finally {
    isLoading.value = false
  }
}

// 忘记密码
const forgotPassword = () => {
  uni.showToast({
    title: '忘记密码功能开发中',
    icon: 'none',
  })
}

onMounted(() => {
  // 确保密码默认隐藏
  showPassword.value = false

  // 检查是否已登录
  const token = uni.getStorageSync('token')
  if (token) {
    uni.reLaunch({
      url: '/pages/index/index',
    })
    return
  }

  // 加载保存的登录凭据
  const hasSavedCredentials = loadSavedCredentials()
  if (hasSavedCredentials) {
    uni.showToast({
      title: '已加载保存的密码',
      icon: 'none',
      duration: 2000,
    })
  }

  loadAppVersion()
})
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background-color: #f0f8ff;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.header-bar {
  width: 100%;
  height: 130px;
  z-index: 10;
  background: linear-gradient(to right, #1a3582, #1890ff);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  .header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx;

    .logo-section {
      display: flex;
      align-items: center;

      .logo-image {
        width: 80rpx;
        height: 80rpx;
        margin-right: 24rpx;
        border-radius: 16rpx;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
      }

      .header-title {
        font-size: 40rpx;
        font-weight: bold;
        color: white;
      }
    }
  }
}
/* 主体内容 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin: auto 20px;
}

/* 登录卡片 */
.login-card {
  background: white;
  border-radius: 28rpx;
  box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.12);
  padding: 86rpx 48rpx;
  margin-bottom: 48rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.8);

  .login-title {
    font-size: 48rpx;
    font-weight: 600;
    color: #1f2937;
    text-align: center;
    margin-bottom: 48rpx;
    display: block;
    letter-spacing: 1rpx;
  }
}
/* 输入框组 */
.input-group {
  position: relative;
  margin-bottom: 32rpx;

  .input-icon {
    position: absolute;
    left: 24rpx;
    top: 50%;
    transform: translateY(-50%);
    color: #1e90ff;
    width: 40rpx;
    height: 40rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 2;

    .icon-text {
      font-size: 32rpx;
    }
  }

  /* 输入框焦点状态 */
  :deep(.u-input) {
    &:focus-within {
      border-color: #00bfff !important;
      box-shadow: 0 0 0 4rpx rgba(30, 144, 255, 0.2) !important;
    }
  }

  /* 调整内置密码切换按钮位置 */
  :deep(.u-input__content__subfix-password-shower) {
    right: 12rpx !important;
    padding-right: 0 !important;

    .up-icon {
      color: #1e90ff !important;
      font-size: 24rpx !important;
    }
  }
}

/* 表单选项 */
.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 32rpx 0 40rpx;

  .remember-text {
    font-size: 28rpx;
    color: #555;
    margin-left: 16rpx;
  }
}

.version-info {
  margin: 24rpx 0 8rpx;
  text-align: center;

  .version-text {
    font-size: 26rpx;
    color: #6b7280;
  }
}

/* 服务标语 */
.service-slogan {
  text-align: center;
  margin-bottom: 48rpx;

  .slogan-text {
    color: #2563eb;
    font-size: 28rpx;
    font-weight: 500;
  }
}

/* 服务功能 */
.service-features {
  display: flex;
  justify-content: space-around;
  margin-bottom: 48rpx;
  padding: 0 20rpx;

  .feature-item {
    background: white;
    border-radius: 16rpx;
    padding: 20rpx 12rpx;
    text-align: center;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
    flex: 1;
    margin: 0 10rpx;
    transition: all 0.3s ease;

    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.12);
    }

    .feature-icon {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 auto 10rpx;
      box-shadow: 0 2rpx 8rpx rgba(59, 130, 246, 0.15);

      .icon-text {
        font-size: 28rpx;
      }
    }

    .feature-text {
      font-size: 20rpx;
      color: #4b5563;
      font-weight: 500;
    }
  }
}

/* 底部信息 */
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background: white;
  padding: 32rpx;
  border-top: 2rpx solid #e5e7eb;

  .footer-icons {
    display: flex;
    justify-content: center;
    margin-bottom: 16rpx;

    .footer-icon {
      width: 64rpx;
      height: 64rpx;
      border-radius: 50%;
      background: #f3f4f6;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 16rpx;

      .icon-text {
        font-size: 28rpx;
        color: #6b7280;
      }
    }
  }

  .footer-text {
    color: #777;
    font-size: 24rpx;
    text-align: center;
    display: block;
    margin-bottom: 8rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
